package com.example.demo.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.api.RpcClient;
import org.apache.flume.api.RpcClientFactory;
import org.apache.flume.event.EventBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Slf4j
@Component
public class LogHelper {

    @Value("${flume.ip}")
    private String ip;

    @Value("${flume.port}")
    private int port;

    @Value("${flume.batchSize}")
    private int batchSize;

    @Value("${flume.enable}")
    private boolean flumeEnable;


    public void sendMsg(String logData) {
        if (!flumeEnable) {
            return;
        }

        RpcClient client = RpcClientFactory.getDefaultInstance(ip, port, batchSize);

        Event event = EventBuilder.withBody(logData, Charset.forName("UTF-8"));
        try {
            client.append(event);
        } catch (EventDeliveryException e) {
            if (log.isErrorEnabled()) {
                log.error("--> sendMsg log exception.", e);
            }
        }
    }

    public static void main(String[] args) {
        LogHelper logHelper = new LogHelper();
        for (int i = 0; i < 10; i++) {
            logHelper.sendMsg("hello " + i);
        }
    }
}
